package com.ms.p2p.plugin.validation;


import com.ms.common.utils.AppContext;
import com.ms.common.utils.WebErrors;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.plugin.AutoRegisterPlugin;
import com.ms.p2p.plugin.validation.annotation.PermissionValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.service.RbacService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/*
 * 权限验证
 * 
 * **/
public class PermissionValidate extends AutoRegisterPlugin implements IValidate {
	@Autowired
	RbacService rbacService;

	private static String PRINCIPAL_SESSION_NAME = "adminUser";

	@Override
	public String getType() {
		return "vallidate";
	}

	@Override
	public String getId() {
		return "permissionValidate";
	}

	@Override
	public String getName() {
		return "权限检验";
	}

	@Override
	public String getVersion() {
		return "1.0.0";
	}

	@Override
	public String getAuthor() {
		return "daimajia";
	}

	@Override
	public void perform(Object... params) {

	}

	@Override
	public void register() {

	}

	@Override
	public WebErrors validate(HttpServletRequest request, WebErrors errors,
							  Validations validations, Map<String, String> decodedUriVariables) {

		AdminUser principal = (AdminUser) AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);

		PermissionValidator[] perm = validations.perms();
		for (PermissionValidator pv : perm) {
			String premission = pv.permission();
			if (!StringUtils.isEmpty(premission)) {


				// 如果非空 那么验证后台权限
				if (!rbacService.checkPremission(principal.getDepart(),
						premission)) {
					errors.addErrorString("您没有这个操作的权限");
				}
			}
		}

		return errors;
	}
}
